<?php

namespace App\Console\Commands;

use App\Services\TtsService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class IdentityAudioTask extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'identity:audio';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '语音合成';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $articles =  DB::table('user_identities')
            ->select(['task_id'])
            ->where('task_id','<>','')
            ->where('audio_url','')
            ->get();

        if ($articles->isNotEmpty()){
            $tts = new TtsService();
            $task_ids = array_column($articles->toArray(),'task_id');
            $result = $tts->ttsQuery($task_ids);
            if ($result){
                foreach ($result as $value){
                    $mp3 = file_get_contents($value['task_result']['speech_url']);
                    $uniqueName = 'audios/'.md5(uniqid()).'.mp3';
                    Storage::disk('oss')->put($uniqueName,$mp3);
                    DB::table('user_identities')
                        ->where('task_id',$value['task_id'])
                        ->update(['audio_url' => 'https://huashimu.oss-cn-beijing.aliyuncs.com/'.$uniqueName]);
                }
            }

        }

        return Command::SUCCESS;
    }
}
